package com.yqwl.controller;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.Connection;
import com.yqwl.common.utils.FastJsonUtil;
import com.yqwl.common.utils.StringUtils;
import com.yqwl.pojo.ColumnInfo;
import com.yqwl.pojo.ColumnNameEnum;
import com.yqwl.pojo.DataDirectory;
import com.yqwl.service.DataDirectorysService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yqwl.common.utils.Constants;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.sql.DriverManager;
import java.util.LinkedHashMap;

/**
 * @author HanMeng
 * @ClassName: GenerateOnLineController
 * @description 后台登陆控制器
 * @createDate 2019年1月21日 下午4:26:08
 */
@Controller
@RequestMapping("login")
@Scope("prototype")
public class GenerateOnLineController {

	@Resource
	private DataDirectorysService dataDirectorysService;

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@RequestMapping(value = "toLogin", method = RequestMethod.GET, produces = Constants.HTML_PRODUCE_TYPE)
	public String get() {
		return "LiquorAdmin/login/login";
	}

	/**
	 * @param account
	 * @param password
	 * @param session
	 * @return String
	 * @Title: login
	 * @description 登陆
	 * @author HanMeng
	 * @createDate 2019年1月9日 上午10:31:28
	 */
	// throws ClassNotFoundException, SQLException
	@ResponseBody
	@RequestMapping(value = "login", method = RequestMethod.GET, produces = Constants.HTML_PRODUCE_TYPE)
	public String login(@RequestParam(value = "hostname") String hostname, @RequestParam(value = "port") String port,
			@RequestParam(value = "database") String database, @RequestParam(value = "user") String user,
			@RequestParam(value = "password") String password,HttpServletResponse response) {
		int code = 0;
		String msg = null;
		if (StringUtils.isBlank(hostname)) {
			code = 1;
			
			msg = "账号或密码错误";
			return FastJsonUtil.getResponseJson(code, msg, null);
		}
		if (StringUtils.isBlank(port)) {
			code = 1;
			msg = "账号或密码错误";
			return FastJsonUtil.getResponseJson(code, msg, null);
		}
		if (StringUtils.isBlank(database)) {
			code = 1;
			msg = "账号或密码错误";
			return FastJsonUtil.getResponseJson(code, msg, null);
		}
		if (StringUtils.isBlank(user)) {
			code = 1;
			msg = "账号或密码错误";
			return FastJsonUtil.getResponseJson(code, msg, null);
		}
		if (StringUtils.isBlank(password)) {
			code = 1;
			msg = "账号或密码错误";
			return FastJsonUtil.getResponseJson(code, msg, null);
		}
		
		try {
			
			Class.forName("com.mysql.jdbc.Driver");
			// 2.URL
			String url = "jdbc:mysql://" + hostname + ":" + port + "/" + database
					+ "?useUnicode=true&characterEncoding=utf8";
			// 3.Connection
			Connection conn = (Connection) DriverManager.getConnection(url, user, password);

			DataDirectory dataDirectory = new DataDirectory();
			// 存储的地方
			dataDirectory.setBaseFielPath("/");
			//String downloadPathUrL=downloadPath.replaceAll("\\\\","\\\\") ;
			//dataDirectory.setBaseFielPath(downloadPathUrL);
			//
			dataDirectory.setDatabaseName(database);
			System.out.println("存储路径：" + dataDirectory.getBaseFielPath());
			System.out.println("数据库：" + dataDirectory.getDatabaseName() + " 数据库字典生成！");
			LinkedHashMap<ColumnNameEnum, ColumnInfo> columnInfoMap = new LinkedHashMap<ColumnNameEnum, ColumnInfo>();
			columnInfoMap.put(ColumnNameEnum.COLUMN_NAME, new ColumnInfo("字段名", 15));
			columnInfoMap.put(ColumnNameEnum.COLUMN_TYPE, new ColumnInfo("数据类型", 15));
			columnInfoMap.put(ColumnNameEnum.IS_NULLABLE, new ColumnInfo("允许为空", 15));
			columnInfoMap.put(ColumnNameEnum.COLUMN_COMMENT, new ColumnInfo("字段说明", 15));
			columnInfoMap.put(ColumnNameEnum.COLUMN_DEFAULT, new ColumnInfo("默认值", 15));
			columnInfoMap.put(ColumnNameEnum.COLUMN_KEY, new ColumnInfo("键值", 15));
			dataDirectory.setTableHeader(columnInfoMap);

			dataDirectorysService.generateDataDirectory(dataDirectory,conn);

				//String fileName =dataDirectory.getDatabaseName() + "数据库字典.docx";
		        String filepath = dataDirectory.getBaseFielPath() + dataDirectory.getDatabaseName() + "数据库字典.docx";
		        
		      //  OutputStream output = null;

		        download(filepath,response,dataDirectory.getDatabaseName() + "数据库字典.docx");
			
		     
							
			code = 0;
			msg = "生成成功 , 如没有找到请检查此文件是否正在被打开";
			return FastJsonUtil.getResponseJson(code, null, null);
		} catch (Exception e) {
			code = -1;
			msg = "生成失败！请检查参数！ 检查另一个程序正在使用此文件，进程无法访问";
			logger.error(e.getMessage(), e);
			return FastJsonUtil.getResponseJson(code, msg, e);
		}
	}
	
	
	
//	@ResponseBody
//	@RequestMapping(value = "down", method = RequestMethod.GET, produces = Constants.HTML_PRODUCE_TYPE)
	 public void download(String filePath, HttpServletResponse response, String fname) throws IOException {
		// filePath ="D:\\liquor_shop数据库字典.docx";    
		// fname="liquor_shop数据库字典.docx"; 
		 System.out.println("down--------start");
		response.setCharacterEncoding("utf-8");
	        response.setHeader("Pragma", "No-Cache");
	        response.setHeader("Cache-Control", "No-Cache");
	        response.setDateHeader("Expires", 0);
	        response.setContentType("application/msexcel; charset=UTF-8");
	        response.setHeader("Content-disposition","attachment; filename=" + URLEncoder.encode(fname, "UTF-8"));// 设定输出文件头
	        ServletOutputStream out = null;
	        FileInputStream in = new FileInputStream(filePath); // 读入文件  
	        out = response.getOutputStream();
	        out.flush();
	        int aRead = 0;
	        while ((aRead = in.read()) != -1 & in != null) {
	            out.write(aRead);
	        }
	        out.flush();
	        in.close();
	        out.close();
	        return;
	    }
	

	
}
